package com.example.mongo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

@Component
public class MongoUtils {

    private static MongoTemplate mongoTemplate;
    @Autowired
    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        MongoUtils.mongoTemplate = mongoTemplate;
    }

    /**
     * 保存对象
     */
    public static String saveObj(Object object) {
        mongoTemplate.save(object);
        return "添加成功";
    }

    /***
     * 根据id查询
     * @param id
     * @return
     */
    public static <T> T getById(String id,Class<T> entityClass) {
        Query query = new Query(Criteria.where("_id").is(id));
        return mongoTemplate.findOne(query, entityClass);
    }

    /**
     * 根据名称查询
     * @param name
     * @return
     */
    public static <T> T getByName(String name,Class<T> entityClass) {
        Query query = new Query(Criteria.where("name").is(name));
        return mongoTemplate.findOne(query, entityClass);
    }

}
